import time
import threading
from concurrent.futures import ThreadPoolExecutor

from playwright.sync_api import sync_playwright


def process_task(task_id):
    """模拟耗时任务，返回任务ID的平方"""
    with sync_playwright() as p:
        browser = p.chromium.launch(headless=False)
        with browser.new_context() as context:
            with context.new_page() as page:
                page.goto('https://baidu.com')
                page.wait_for_timeout(5)
                print(f'{task_id}:{threading.get_ident()}')
                page.locator("#kw").fill("python")
                page.get_by_role("button", name="百度一下").click()
                return page.content()
                # print(f'{page.title()},{}')
    # print(f"开始处理任务 {task_id}（线程: {threading.get_ident()}）")
    # time.sleep(0.1)  # 模拟1秒的处理时间
    # print(f"完成任务 {task_id}")
    # return task_id ** 2


def thread_poll_main():
    # 创建包含3个工作线程的线程池
    with ThreadPoolExecutor(max_workers=50) as executor:
        # 提交10个任务（任务ID从0到9）
        # submit方法返回Future对象，代表异步执行的任务
        futures = [executor.submit(process_task, i) for i in range(100)]

        print("\n所有任务已提交，等待完成...\n")

        # 按完成顺序处理结果（使用as_completed）
        from concurrent.futures import as_completed
        for future in as_completed(futures):
            try:
                task_id = futures.index(future)  # 获取对应的任务ID
                result = future.result()  # 获取任务结果（如果任务失败会抛出异常）
                print(f"任务 {task_id} 的结果: {result}")
            except Exception as e:
                print(f"任务 {task_id} 失败: {e}")


if __name__ == "__main__":
    start_time = time.time()
    thread_poll_main()
    print(f"\n所有任务处理完成，耗时: {time.time() - start_time:.2f} 秒")
    # process_task(1)